<template>
  <n-card ref="receiptContent">
    <div class="page-body">
      <div class="mb-4 font-bold text-2xl font-black">
        <span>您的设备回收订单已完结</span>
      </div>
      <div class="flex justify-between items-center">
        <n-image width="80" src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg" />
        <div class="text-right">
          <div class="text-lg">
            <span>订单号: </span>
            <span class="font-bold">#{{ purchaseInfo.id }}</span>
          </div>
          <div class="text-lg mt-1">
            <span>创建事件: </span>
            <span class="font-bold">{{ purchaseInfo.createTime }}</span>
          </div>
        </div>
      </div>
      <div class="mt-4">
        <span class="text-lg font-bold">订单交易项汇总</span>
      </div>
      <div class="mt-2">
        <div class="product-item" v-for="item in purchaseItems" :key="item.id">
          <div class="product-info">
            <div>
              <span>{{ item.variantName }}</span>
            </div>
            <div class="mt-1">
              <span>序列号/IMEI: {{ item.snName }}</span>
            </div>
          </div>
          <div class="product-amount">
            <span>X{{ item.quantity }}</span>
            <span>{{ currencyFormat(item.rowTotal) }}</span>
          </div>
        </div>
      </div>
      <div class="mt-2 price-info">
        <div class="price-money">
          <div class="price-item">
            <span>应收总金额: </span>
            <span class="price-item-amount">
              {{ currencyFormat(purchaseInfo.total) }}
            </span>
          </div>
          <div class="price-item border-b pb-2">
            <span>实收总金额: </span>
            <span class="price-item-amount">
              {{ currencyFormat(purchaseInfo.paidAmount) }}
            </span>
          </div>
          <div class="mt-2 mb-2">
            <span class="font-base font-black">商家付款明细</span>
          </div>
          <div v-for="item in paymentsList" :key="item.id" class="mb-2">
            <div class="price-item">
              <span>{{ getPaymentMethodName(item.method) }}: </span>
              <span class="price-item-amount">
                {{ currencyFormat(item.amount) }}
              </span>
            </div>
            <div class="text-right text-sm text-gray-500">
              <span>{{ item.createTime }}</span>
            </div>
          </div>
        </div>
      </div>
      <div class="mt-2 customer-store-info">
        <div>
          <div><span class="text-lg font-bold">客户信息</span></div>
          <div class="mt-1">
            <span class="text-base font-black">{{ customerInfo.name }}</span>
          </div>
          <div class="mt-1">
            <span class="text-gray-500">{{ customerInfo.phoneNumber }}</span>
          </div>
        </div>
        <div class="text-right">
          <div><span class="text-lg font-bold">商家信息</span></div>
          <div class="mt-1">
            <span class="text-base font-black">
              {{ companySettings.companyName }}
            </span>
          </div>
          <div class="mt-1">
            <span class="text-gray-500">{{ companySettings.address }}</span>
          </div>
        </div>
      </div>
      <div class="mt-2 help-info">
        <div>
          <span class="text-gray-500">
            如遇到疑问，可以通过以下联系方式与我们取得联系：
          </span>
        </div>
        <div class="mt-2">
          <span class="text-gray-500">联系电话:</span>
          <span class="ml-2 font-black text-base font-bold">
            {{ companySettings.contactPhone }}</span>
        </div>
        <div class="mt-2" v-if="companySettings.contactEmail">
          <span class="text-gray-500">邮箱:</span>
          <span class="ml-2 font-black text-base font-bold">
            {{ companySettings.contactEmail }}
          </span>
        </div>
      </div>
      <div class="mt-2 help-info">
        <div v-html="tradeInTerm"></div>
      </div>
    </div>
  </n-card>
</template>
<script setup lang="ts">
import { computed, nextTick, ref, watch } from "vue";
import { get, isEmpty } from "lodash-es";
import { usePrint } from "@/common/hooks/usePrint.ts";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import { getTradeInReceiptData } from "@/api/tradein/tradein.api";
import {
  getCompanySetting,
  getTermsSettings,
} from "@/api/settings/settings.api";
import { getPaymentMethodName } from "@/common/utils/payment/index";
import { ITradeInReceiptProps } from "./props";
import { TradeInReceiptDataVO } from "@/types/model/tradein/vos/tradein.vo";
import { TERM_TYPE } from "@/constants/terms";

const { receiptContent, handlePrint } = usePrint();

const props = defineProps<ITradeInReceiptProps>();

const receiptData = ref<TradeInReceiptDataVO>({} as TradeInReceiptDataVO);
const showReceipt = ref<boolean>(false);
const companySettings = ref<any>({});
const tradeInTerm = ref<string>("");

watch(
  () => props.orderId,
  (newVal) => {
    if (newVal) {
      receiptData.value = {} as TradeInReceiptDataVO;
    }
  }
);

const purchaseInfo = computed(() => {
  return get(receiptData.value, "posPurchase") || {};
});

const purchaseItems = computed(() => {
  return get(receiptData.value, "items") || [];
});

const customerInfo = computed(() => {
  return get(receiptData.value, "customer") || {};
});

const paymentsList = computed(() => {
  return get(receiptData.value, "payments") || [];
});

const emit = defineEmits(["printed"]);

const print = async () => {
  if (props.orderId) {
    try {
      // 加载数据
      if (isEmpty(receiptData.value)) {
        const result = await getTradeInReceiptData(props.orderId);
        receiptData.value = get(result, "result") || {};

        const compSettingResult = await getCompanySetting();
        companySettings.value = get(compSettingResult, "result") || {};

        const termsResult = await getTermsSettings();
        const _termsSettings = get(termsResult, "result") || [];
        tradeInTerm.value = _termsSettings.find(
          (item: any) => item.type === TERM_TYPE.TRADE_IN
        )?.content;
      }

      // 显示打印内容
      showReceipt.value = true;

      // 确保内容已渲染
      await nextTick();

      // 添加延迟确保内容完全渲染
      console.log("准备打印", receiptData.value);
      console.log("打印元素存在:", !!receiptContent.value);

      if (!receiptContent.value) {
        console.error("打印元素未找到");
        return;
      }

      // 执行打印
      handlePrint();

      // 打印完成后延迟隐藏内容
      setTimeout(() => {
        showReceipt.value = false;
        emit("printed");
      }, 1000); // 延长延迟时间
    } catch (error) {
      console.error("打印过程出错", error);
      showReceipt.value = false;
    }
  } else {
    console.error("缺少订单ID");
  }
};

defineExpose({
  print,
});
</script>
<style lang="scss" scoped>
.page-body {
  background: #fff;

  .product-item {
    @apply flex justify-between items-center border-b text-base pb-2;

    +.product-item {
      @apply mt-2;
    }

    .product-info {
      @apply basis-2/3;
    }

    .product-amount {
      @apply flex flex-1 justify-between items-center font-bold text-slate-950;
    }
  }

  .price-info {
    @apply flex justify-end border-b;

    .price-money {
      @apply basis-1/2;

      .price-item {
        @apply flex justify-between items-center text-gray-500;

        .price-item-amount {
          @apply text-black font-bold;
        }
      }
    }
  }

  .customer-store-info {
    @apply flex justify-between items-center border-b pb-2;

    >div {
      @apply flex-1;
    }
  }
}
</style>

<style lang="scss" scoped>
/* 添加打印专用样式 */
@media print {

  body * {
    visibility: hidden;
  }

  /* 确保n-card及其所有父元素都可见 */
  .n-card,
  .n-card *,
  .page-body,
  .page-body * {
    color: #222;
    visibility: visible !important;
  }

  .n-card {
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    /* 移除可能影响打印的样式 */
    box-shadow: none !important;
    border: none !important;
  }
}
</style>
